package com.ithrima.waimaidemo.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ithrima.waimaidemo.common.CustomException;
import com.ithrima.waimaidemo.dao.SetmealMapper;
import com.ithrima.waimaidemo.pojo.Setmeal;
import com.ithrima.waimaidemo.pojo.SetmealDish;
import com.ithrima.waimaidemo.pojo.SetmealDto;
import com.ithrima.waimaidemo.service.ISetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Slf4j
@Service

public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {


    @Autowired
    SetmealDishServiceImpl setmealDishService;
    @Autowired
    SetmealServiceImpl setmealService;
    @Override
    public void saveWithDish(SetmealDto setmealDto) {

        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes);

    }

    @Override
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);
        int count = this.count(wrapper);
        if(count>0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        this.removeByIds(ids);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId,ids);
        setmealDishService.remove(queryWrapper);


    }

    @Override
    public void updateSetmealStatus(Integer status, List<Long> ids) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ids!= null ,Setmeal::getId,ids);
        List<Setmeal> list = setmealService.list(wrapper);
        list.forEach(new Consumer<Setmeal>() {
            @Override
            public void accept(Setmeal setmeal) {
               if(setmeal!= null){
                   setmeal.setStatus(status);
                    setmealService.updateById(setmeal);
               }
            }
        });

    }
}
